package com.whmskj.xjlhbc.service.impl;

import com.whmskj.xjlhbc.dto.EnergyConsumption.*;
import com.whmskj.xjlhbc.mapper.EnergyConsumptionMapper;
import com.whmskj.xjlhbc.service.EnergyConsumptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Sakura
 * @Date: 2025/8/21 10:34
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class EnergyConsumptionServiceImpl implements EnergyConsumptionService {
    @Autowired
    private EnergyConsumptionMapper energyMapper ;
    /**
     * 获取车间能耗数据
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param workshop  车间名称
     * @return
     */
    @Override
    public WorkShopEnergySummaryVo getWorkshopEnergySummary(Date startDate, Date endDate, String workshop) {
        WorkShopEnergySummaryVo summaryVo = new WorkShopEnergySummaryVo();

        // 查询每日数据
        List<WorkShopEnergyDto> dailyData = energyMapper.selectDailyEnergyConsumption(startDate, endDate, workshop);
        summaryVo.setDailyData(dailyData);

        // 查询合计数据
        WorkShopEnergySummaryVo totalData = energyMapper.selectTotalEnergyConsumption(startDate, endDate, workshop);
        summaryVo.setTotalEnergyConsumption(totalData.getTotalEnergyConsumption());
        summaryVo.setTotalElectricityFee(totalData.getTotalElectricityFee());

        return summaryVo;
    }

    /**
     * 获取车间能耗详情
     *
     * @param workshop 车间名称
     * @return
     */
    @Override
    public WorkshopEnergyResponse getEnergyDetailsByWorkshopAndDate(String workshop, Date queryDate) {
        // 获取启用的电费单价
        BigDecimal unitPrice = energyMapper.getActiveUnitPrice();
        if (unitPrice == null) {
            throw new RuntimeException("未找到启用的电费单价");
        }

        // 查询电表能耗详情（指定日期）
        List<MeterDetail> meterDetails = energyMapper.selectEnergyDetailsByDate(
                workshop, queryDate, unitPrice);

        // 由于只查询一天的数据，直接创建单个DateGroup
        WorkshopEnergyResponse response = new WorkshopEnergyResponse();
        List<DateGroup> dateGroups = new ArrayList<>();

        DateGroup dateGroup = new DateGroup();
        dateGroup.setDate(queryDate);

        // 按车间分组
        Map<String, List<MeterDetail>> groupedByWorkshop = meterDetails.stream()
                .collect(Collectors.groupingBy(MeterDetail::getWorkshop));

        List<WorkshopGroup> workshopGroups = new ArrayList<>();

        for (Map.Entry<String, List<MeterDetail>> workshopEntry : groupedByWorkshop.entrySet()) {
            WorkshopGroup workshopGroup = new WorkshopGroup();
            workshopGroup.setWorkshop(workshopEntry.getKey());

            // 按配电室分组
            Map<String, List<MeterDetail>> groupedByDistributionRoom = workshopEntry.getValue().stream()
                    .collect(Collectors.groupingBy(MeterDetail::getDistributionRoomName));

            List<DistributionRoomGroup> distributionRooms = new ArrayList<>();

            for (Map.Entry<String, List<MeterDetail>> roomEntry : groupedByDistributionRoom.entrySet()) {
                DistributionRoomGroup roomGroup = new DistributionRoomGroup();
                roomGroup.setDistributionRoomName(roomEntry.getKey());
                roomGroup.setMeterDetails(roomEntry.getValue());

                // 计算配电室总用电量和总金额
                BigDecimal roomTotalDay = roomEntry.getValue().stream()
                        .map(MeterDetail::getDayConsumption)
                        .filter(Objects::nonNull)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                BigDecimal roomTotalAmount = roomEntry.getValue().stream()
                        .map(MeterDetail::getDayCost)
                        .filter(Objects::nonNull)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                roomGroup.setTotalDay(roomTotalDay);
                roomGroup.setTotalAmount(roomTotalAmount);

                distributionRooms.add(roomGroup);
            }

            workshopGroup.setDistributionRooms(distributionRooms);

            // 计算车间总用电量和总金额
            BigDecimal workshopTotalDay = workshopEntry.getValue().stream()
                    .map(MeterDetail::getDayConsumption)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            BigDecimal workshopTotalAmount = workshopEntry.getValue().stream()
                    .map(MeterDetail::getDayCost)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            workshopGroup.setTotalDay(workshopTotalDay);
            workshopGroup.setTotalAmount(workshopTotalAmount);

            workshopGroups.add(workshopGroup);
        }

        dateGroup.setWorkshops(workshopGroups);

        // 计算日期总用电量和总金额
        BigDecimal dateTotalDay = meterDetails.stream()
                .map(MeterDetail::getDayConsumption)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal dateTotalAmount = meterDetails.stream()
                .map(MeterDetail::getDayCost)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        dateGroup.setTotalDay(dateTotalDay);
        dateGroup.setTotalAmount(dateTotalAmount);

        dateGroups.add(dateGroup);
        response.setDateGroups(dateGroups);

        return response;
    }
}
